package com.xh.core.util;

import com.xh.core.bean.SubStringBean;
import com.xh.tools.question.util.RegexUtils;
import org.seimicrawler.xpath.core.node.Html;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * @Author daiwei
 * @Description
 * @Date 2018/8/11 11:48
 **/
public class StringUtils {
    private static String letterList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static Random random = new Random(System.currentTimeMillis());

    private static final String START_BLANK = "^( | |&nbsp;)";

    private static final String END_BLANK = "( | |&nbsp;)$";

    public static String getLetterByNo(int no) {
        return String.valueOf(letterList.charAt(no - 1));
    }

    public static boolean isEmpty(String str) {
        if (str == null || str.trim().equals("")) {
            return true;
        }
        return false;
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    /**
     * 获取网址host
     *
     * @param url
     * @return
     */
    public static String getUrlHost(String url) {
        if (url == null || url.trim().equals("")) {
            return "";
        }
        String host = "";
        Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
        Matcher matcher = p.matcher(url);
        if (matcher.find()) {
            host = matcher.group();
        }
        return host;
    }

    /**
     * 生成随机数
     *
     * @param length 位数
     * @return
     */
    public static String randomNumber(int length) {
        String bases = "0123456789";
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(bases.length() - 2) + 1;
            result.append(bases.substring(index, index + 1));
        }
        return result.toString();
    }

    /**
     * 生成随机字符串（不包含10io）
     *
     * @param length 位数
     * @return
     */
    public static String randomString(int length) {
        String bases = "23456789abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(bases.length() - 2) + 1;
            result.append(bases.substring(index, index + 1));
        }
        return result.toString();
    }

    /**
     * 下划线转驼峰格式格式
     *
     * @param str 下划线格式
     * @return 驼峰格式
     */
    public static String underline2Fump(String str) {

        String[] split = str.split("_");
        StringBuilder builder = new StringBuilder();
        builder.append(split[0]);// 拼接第一个字符

        // 如果数组不止一个单词
        if (split.length > 1) {
            for (int i = 1; i < split.length; i++) {
                // 去掉下划线，首字母变为大写
                String string = split[i];
                String substring = string.substring(0, 1);
                split[i] = string.replaceFirst(substring, substring.toUpperCase());
                builder.append(split[i]);
            }
        }

        return builder.toString();
    }

    /// 转全角的函数(SBC case)
    ///
    ///任意字符串
    ///全角字符串
    ///
    ///全角空格为12288，半角空格为32
    ///其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
    ///
    public static String toSBC(String input) {
        // 半角转全角：
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 32) {
                c[i] = (char) 12288;
                continue;
            }
            if (c[i] < 127)
                c[i] = (char) (c[i] + 65248);
        }
        return new String(c);
    }

    /**/
    // /
    // / 转半角的函数(DBC case)
    // /
    // /任意字符串
    // /半角字符串
    // /
    // /全角空格为12288，半角空格为32
    // /其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
    // /
    public static String toDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    /// <summary>
    /// 中文标点符号替换成英文
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static String replaceChsCharToEng(String text) {
        String s1 = "。；：，？！“”‘’＜＞﹤﹥［］｛｝／＼｜－＝＿＋｀～！＠＃＄％＾＆＊（）";
        String s2 = ".;:,?!\"\"''<><>[]{}/\\|-=_+`~!@#$%^&*()";

        char[] s2c = s2.toCharArray();
        char[] c = text.toCharArray();
        for (int i = 0; i < c.length; i++) {
            int n = s1.indexOf(c[i]);
            if (n != -1) c[i] = s2c[n];
        }
        return new String(c);
    }

    /**
     * 从文本中获取所有latex公式
     *
     * @param text
     * @return
     */
    public static List<SubStringBean> getLatexFromText(String text) {
        List<SubStringBean> result = new ArrayList<>();
        if (StringUtils.isEmpty(text)) {
            return result;
        }
        //提取$x=a+b$形式的公式
        int startIndex = text.indexOf('$');
        while (startIndex >= 0) {
            if (startIndex != 0 && '\\' == text.charAt(startIndex - 1)) {
                startIndex = text.indexOf('$', startIndex + 1);
                continue;
            }
            int endIndex = text.indexOf('$', startIndex + 1);
            if (endIndex >= 0) {
                while ('\\' == text.charAt(endIndex - 1)) {
                    endIndex = text.indexOf('$', endIndex + 1);
                }
                if (endIndex < 0) {
                    break;
                }
                result.add(new SubStringBean(startIndex, endIndex, text.substring(startIndex + 1, endIndex)));
                startIndex = text.indexOf('$', endIndex + 1);
                continue;
            }
            break;
        }
        return result;
    }


    /**
     * 删除字符串中的一个字符
     *
     * @param s
     * @param pos
     * @return
     */
    public static String removeCharAt(String s, int pos) {
        return s.substring(0, pos) + s.substring(pos + 1);
    }

    public static String list2Str(List list) {
        if (list == null) {
            return "";
        }
        String str = list.toString();
        str = str.substring(1, str.lastIndexOf("]"));
        return str;
    }

    public static String joinList(List<String> list, String split) {
        if (list == null || list.size() == 0) {
            return "";
        }
        if (split == null) {
            split = "";
        }
        StringBuilder sb = new StringBuilder();
        for (String item : list) {
            if (sb.length() > 0) {
                sb.append(split);
            }
            sb.append(item);
        }
        return sb.toString();
    }

    /**
     * 计算相似度
     */
    public static double SimilarDegree(String strA, String strB) {
        String newStrA = removeSign(strA);
        String newStrB = removeSign(strB);
        //用较大的字符串长度作为分母，相似子串作为分子计算出字串相似度
        int temp = Math.max(newStrA.length(), newStrB.length());
        int temp2 = longestCommonSubstring(newStrA, newStrB).length();
        DecimalFormat df = new DecimalFormat("#.00");
        return Double.valueOf(df.format(temp2 * 100 / temp));
    }

    /**
     * 将字符串的所有数据依次写成一行
     **/
    public static String removeSign(String str) {
        StringBuffer sb = new StringBuffer();
        //遍历字符串str,如果是汉字数字或字母，则追加到ab上面
        for (char item : str.toCharArray())
            if (charReg(item)) {
                sb.append(item);
            }
        return sb.toString();
    }

    /**
     * 判断字符是否为汉字，数字和字母，
     * 因为对符号进行相似度比较没有实际意义，故符号不加入考虑范围。
     */
    public static boolean charReg(char charValue) {
        return (charValue >= 0x4E00 && charValue <= 0X9FA5) || (charValue >= 'a' && charValue <= 'z')
                || (charValue >= 'A' && charValue <= 'Z') || (charValue >= '0' && charValue <= '9');
    }

    /**
     * 求公共子串，采用动态规划算法。
     * 其不要求所求得的字符在所给的字符串中是连续的。
     **/
    public static String longestCommonSubstring(String strA, String strB) {
        char[] chars_strA = strA.toCharArray();
        char[] chars_strB = strB.toCharArray();
        int m = chars_strA.length;
        int n = chars_strB.length;

        int[][] matrix = new int[m + 1][n + 1];
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (chars_strA[i - 1] == chars_strB[j - 1]) {
                    matrix[i][j] = matrix[i - 1][j - 1] + 1;
                } else {
                    matrix[i][j] = Math.max(matrix[i][j - 1], matrix[i - 1][j]);
                }
            }
        }

        char[] result = new char[matrix[m][n]];
        int currentIndex = result.length - 1;
        try {
            while (matrix[m][n] != 0) {
                if (matrix[n] == matrix[n - 1]) {
                    n--;
                } else if (matrix[m][n] == matrix[m - 1][n]) {
                    m--;
                } else {
                    result[currentIndex] = chars_strA[m - 1];
                    currentIndex--;
                    n--;
                    m--;
                }
            }
        } catch (Exception e) {
            return new String(result);
        }
        return new String(result);
    }

    public static String removeStartAndEndBlank(String text) {
        if (isEmpty(text)) {
            return text;
        }
        text = removeStartBlank(text);
        text = removeEndBlank(text);
        return text;
    }

    public static String removeStartBlank(String s) {
        while (com.xh.tools.question.util.RegexUtils.Match(s, START_BLANK)) {
            s = s.replaceFirst(START_BLANK, "");
            s = removeStartBlank(s);
        }
        return s;
    }

    public static String removeEndBlank(String s) {
        while (RegexUtils.Match(s, END_BLANK)) {
            s = replaceLast(s, END_BLANK, "");
            s = removeEndBlank(s);
        }
        return s;
    }

    public static String replaceLast(String text, String regex, String replacement) {
        return text.replaceFirst("(?s)(.*)" + regex, "$1" + replacement);
    }
}
